import React, {useState, useEffect}from 'react';
import { Col, Select, Radio, Icon, message, Button } from 'antd';
import services from '../../../services/api';
import { cloneDeep } from 'lodash';
import moment from 'moment';
import '../index.less'
import LineMap from './line';
import BarMap from './bar';
const {Option} = Select
export default function lineMap(props) {
  const [typeSelect, setTypeSelect] = useState('3');
  const [typeGroup, setTypeGroup] = useState('1');
  const [seeType, setSeeType] = useState('request');
  const [mapData, setMapData] = useState([]);
  const [rawMapData, setRawMapData] = useState(props.data)
  const [showLeftBtn, setLeftBtn] = useState(false);
  const [showRightBtn, setRightBtn] = useState(false);
  const [preveIndex, setPreveIndex] = useState(0);
  const [isPercentage, setIsPercentage] = useState(false);
  const [isDisable, setIsDisable] = useState(false); //是否禁用一些选择时间
  useEffect(() => {
    const endTime = moment(props.requestParam.end).valueOf();
    const startTime = moment(props.requestParam.start).valueOf();
    const times = moment(endTime).diff(moment(startTime), 'days');
    if (times > 40) {
      setIsDisable(true);
    } else {
      setIsDisable(false);
    }
    if (!props.isStopTime) {
      if (times < 7 ) {
        setTypeSelect('4');
      } else if (times > 7 && times < 120 ) {
        setTypeSelect('5');
      } else if ( times > 120)  {
        setTypeSelect('6');
      }
    }
  },[props.requestParam])
  useEffect(() => {
    // setData(props.data, '1');
    // console.log(props.requestParam);
    if (Object.keys(props.requestParam).length && props.requestParam.start) {
      requestTrend();
    }
  },[props.data, props.requestParam]);
  function rateRatio(data) {
    const typeList = ['pass', 'refuse', 'reject'];
    const nameList = {
      'pass': '通过率', 
      'refuse': '复核率',
      'reject': '拒绝率'
    }
    const total = data.find(it => it.key === 'total'); // 总请求量
    const newList = data.filter(it => {
      if (typeList.includes(it.key)) {
        it.name = nameList[it.key];
        it.value.forEach((item,index) => {
          item.requests =  (total.value[index].requests && ((item.requests / total.value[index].requests) * 10000).toFixed() / 100) || 0;
        })
        return it;
      } else {
        return false
      }
    });
    return newList;
  };
  function getTimes(types, counts) {
    let {current_start, current_end} = getCurrentTime(types, counts);
    if (counts) {
      setRightBtn(true);
    }
    if (moment(current_start) >= moment(current_end)) {
      setLeftBtn(true);
    } else {
      setLeftBtn(false);
    }
    if (moment(current_start) >= moment(props.requestParam.start)) {
      setLeftBtn(true);
    } else {
      current_start = props.requestParam.start;
    }
    const params = {
      type: types,
      ...props.requestParam,
      current_start,
      current_end
    }
    return params
  }
  // 请求趋势分析
  function requestTrend(nums, type) {
    let counts = nums || 0;
    const types = type || typeSelect;
    let isHideRightBtn = true;
    if (type && typeSelect !== type) {
      setTypeSelect(type);
      isHideRightBtn = false;
      counts = 0;
    } else if (!nums && !type) {
      isHideRightBtn = false;
      counts = 0;
    }
    let params = getTimes(types, counts);
    services[props.actionType].requestTrend(params).then(res => {
      if (!res.code) {
        if (!isHideRightBtn) {
          setPreveIndex(0);
          setRightBtn(isHideRightBtn);
        }
        setRawMapData(res.data);
        const lists = cloneDeep(res.data);
        setData(lists, typeGroup, seeType);
      } else {
        message.error(res.msg)
      }
    })
  };
  // 下载
  function downFile () {
    let params = getTimes(typeSelect, preveIndex);
    props.downFile && props.downFile(params, 'd1');
  };
  // 选择查看方式
  function handleChange(value) {
     let lists = cloneDeep(rawMapData);
     if (value === 'ratio') {
      setIsPercentage(true);
     } else {
      setIsPercentage(false);
     }
     setSeeType(value);
     setData(lists, typeGroup, value);
    //  setMapData(lists);
  };
  // 选择颗粒度
  function handleGrainChange(value) {
    // setTypeSelect(value);
    requestTrend(preveIndex, value);
  };
  function getGroupChange(e) {
    const values = e.target.value;
    let lists = cloneDeep(rawMapData);
    setData(lists, values, seeType);
    setTypeGroup(values);
  }
  function setData(data,type, ratioType) {
    let types = 'line';
    if (type === '2') {
      types = 'bar';
    }
    let lists =  data.map(item => {
      item.type = types;
      return item;
    })
    if (ratioType === 'ratio') {
      lists = rateRatio(lists)
    }
    setMapData(lists);
  }
  function prevData() {
    const nums = preveIndex + 1
    setPreveIndex(nums);
    requestTrend(nums);
  };
  function nextData () {
    if (preveIndex > 0) {
      const nums = preveIndex - 1
      setPreveIndex(nums);
      requestTrend(nums);
    } else {
      setRightBtn(false)
    }
  };
  function getCurrentTime(riskTrendType, nums) {
    let current_end = moment(props.requestParam.end).format('YYYY-MM-DD HH:mm:ss');
    let current_start = moment(props.requestParam.start).format('YYYY-MM-DD HH:mm:ss');
    const endTime = moment(props.requestParam.end).valueOf();
    switch (riskTrendType) {
      case '1':
        current_end = moment(endTime - nums * 3600000).format('YYYY-MM-DD HH:mm:ss');
        current_start = moment(endTime - (nums + 1) * 3600000).format('YYYY-MM-DD HH:mm:ss');
        break;
      case '2':
        current_end = moment(endTime - nums * 6 * 3600000).format('YYYY-MM-DD HH:mm:ss');
        current_start = moment(endTime - (nums + 1) * 6 * 3600000).format('YYYY-MM-DD HH:mm:ss');

        break;
      case '3':
        current_end = moment(endTime - nums * 24 * 3600000).format('YYYY-MM-DD HH:mm:ss');
        current_start = moment(endTime - (nums + 1) * 24 * 3600000).format('YYYY-MM-DD HH:mm:ss');
        break;
      case '4':
          current_end = moment(endTime - nums * 60 * 3600000).format('YYYY-MM-DD HH:mm:ss');
          current_start = moment(endTime - (nums + 1) * 60 * 3600000).format('YYYY-MM-DD HH:mm:ss');
          break;
      default:
        break;
    }

    return { current_start, current_end };
  }
  return (
    <>
      <div className='title-dash-boxs'>
        <p>请求趋势统计</p>
        <div className='title-dash-children'>
          { !props.isDisable ? (<> {!props.isDownTitle ? <p onClick={downFile}>下载数据</p> : ''}
          <div>
            <Select
              style={{ width: 150 }}
              placeholder="请选择"
              value={seeType}
              onChange={handleChange}
            >
            <Option value="request">按请求量查看</Option>
            <Option value="ratio">按比率查看</Option>
           </Select>
          </div>
          <div>
            <Select
              style={{ width: 150 }}
              value={typeSelect}
              placeholder="请选择展示粒度"
              onChange={handleGrainChange}
            >
             <Option disabled={isDisable} value={'1'}>每分钟</Option>
             <Option disabled={isDisable} value={'2'}>每5分钟</Option>
             <Option disabled={isDisable} value={'3'}>每30分钟</Option>
             <Option disabled={isDisable} value={'4'}>每小时</Option>
             <Option value={'5'}>每天</Option>
             <Option value={'6'}>每月</Option>
           </Select>
          </div></>) : (<>{''}</>)
          }
          <div>
            <Radio.Group
                value={typeGroup}
                onChange={getGroupChange}
            >
              <Radio.Button
                 value='1'
              >
                <Icon type='line-chart' />
              </Radio.Button>
              <Radio.Button
                 value='2'
              >
                <Icon type='bar-chart' />
              </Radio.Button>
            </Radio.Group>
          </div>
        </div>
      </div>
      <div className='request-trend-style risk-trend-box'>
         <Col key={1} span={24}>
            {(typeGroup === '1' && (<LineMap isLengen={true} isPercentage={isPercentage} data={mapData}></LineMap>))
            || (<BarMap isLengen={true} isPercentage={isPercentage} data={mapData}></BarMap>)}
         </Col>
           { (typeSelect !== '5' && typeSelect !== '6')  ? (
            <div>
                  {showLeftBtn ? (
                    <Button onClick={() => prevData()} className='prev-btn' shape='circle'>
                      <Icon type='left' />
                    </Button>
                   ) : (
                    ''
                  )} 
                {showRightBtn ? (
                    <Button onClick={() => nextData()} className='next-btn' shape='circle'>
                      <Icon type='right' />
                    </Button>
                  ) : (
                    ''
                  )}
                </div>
              ) : (
                ''
              )} 
      </div>
    </>
  )
}